<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Utils\ResponseResult\JsonResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UserController extends Controller
{
    //
    public function list(Request $request)
    {
        $name = $request->input("name");
        $gender = $request->input("gender") ?? -1;
        $status = $request->input("status") ?? -1;
        $begin = $request->input("begin");
        $end = $request->input("end");
        $per_page = $request->input("per_page", env("DEFAULT_PAGE"));
        $list = DB::table("users")
            ->whereNull("deleted_at")
            ->where(function ($query) use ($name, $gender, $begin, $end, $status) {
                if ($name !== null) {
                    $query->where("name", "like", "%{$name}%");
                }
                if ($gender != -1) {
                    $query->where("gender", $gender);
                }
                if ($status != -1) {
                    $query->where("status", $status);
                }
                if ($begin !== null) {
                    $query->whereDate("birth", ">=", $begin);
                }
                if ($end !== null) {
                    $query->whereDate("birth", "<=", $end);
                }
            })
            ->paginate($per_page)
            ->withQueryString();
        return JsonResult::success($list, "查询成功");
    }
    public function create(Request $request)
    {
        $name = $request->input("name");
        $email = $request->input("email");
        $password = $request->input("password");
        $cellphone = $request->input("cellphone");
        $gender = $request->input("gender");
        $birth = $request->input("birth");
        $avatar = $request->input("avatar");

        // 1.验证请求
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:3|max:20',
            'password' => 'required|min:6|max:20',
            'email' => 'required|email',
            'cellphone' => 'nullable',
            'gender' => 'nullable',
            'birth' => 'nullable',
            'avatar' => 'nullable',
        ]);
        if ($validator->fails()) {
            return JsonResult::forbidden(null, "请求参数错误");
        }

        // 2.验证用户是否存在（用户名，邮箱）
        $userCount = DB::table("users")
            ->where("name", $name)
            ->orWhere("email", $email)
            ->count();
        if ($userCount > 0) {
            return JsonResult::forbidden(null, "用户/邮箱已存在");
        }

        // 3.注册用户
        // 3.1 密码加密
        $password = Hash::make($password);

        // 处理头像上传或直接传文件名
        $avatar = null;
        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $ext = strtolower($file->getClientOriginalExtension());
            $uuid = Str::uuid()->toString();
            $fileName = $uuid . '.' . $ext;
            $path = $file->storeAs('', $fileName, 'avatar');
            if (!$path) {
                return JsonResult::forbidden(null, '头像上传失败');
            }
            $avatar = $fileName;
        } elseif ($request->filled('avatar')) {
            $avatar = $request->input('avatar');
        }

        // 3.2 保存用户信息
        $insertData = [
            "name" => $name,
            "email" => $email,
            "password" => $password,
            "cellphone" => $cellphone,
            "gender" => $gender,
            "birth" => $birth,
            "created_at" => now(),
        ];
        if ($avatar) {
            $insertData["avatar"] = $avatar;
        }
        $id = DB::table("users")->insertGetId($insertData);
        if ($id <= 0) {
            return JsonResult::forbidden(null, "创建用户失败");
        }

        // 4.返回结果
        return JsonResult::created(null, "创建用户成功");
    }
    public function edit(Request $request)
    {
        $rules = [
            "id" => "required",
            "name" => "nullable|min:3|max:20",
            "email" => "nullable|email",
            "cellphone" => "nullable",
            "password" => "nullable|min:6|max:20",
            "gender" => "nullable",
            "birth" => "nullable",
            "status" => "nullable",
            "avatar" => "nullable"
        ];

        if (Validator::make($request->all(), $rules)->fails()) {
            return JsonResult::forbidden(null, "请求参数错误");
        }

        $id = $request->input("id");
        $data = $request->only(["name", "email", "cellphone", "gender", "birth", "status"]);

        // 如果提供了密码，则进行加密
        if ($request->has("password")) {
            $data["password"] = Hash::make($request->input("password"));
        }

        // 处理头像上传或直接传文件名
        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $ext = strtolower($file->getClientOriginalExtension());
            $uuid = Str::uuid()->toString();
            $fileName = $uuid . '.' . $ext;
            $path = $file->storeAs('', $fileName, 'avatar');
            if (!$path) {
                return JsonResult::forbidden(null, '头像上传失败');
            }
            $data['avatar'] = $fileName;
        } elseif ($request->filled('avatar')) {
            // 如果avatar是字符串（如前端直接传文件名）
            $data['avatar'] = $request->input('avatar');
        }

        // 移除空值（但保留avatar字段）
        $data = array_filter($data, function ($value, $key) {
            return $value !== null || $key === 'avatar';
        }, ARRAY_FILTER_USE_BOTH);

        if (empty($data)) {
            return JsonResult::forbidden(null, "没有要更新的数据");
        }

        $result = DB::table("users")->where("id", $id)->update($data);

        if ($result) {
            return JsonResult::success(null, "编辑用户成功");
        } else {
            return JsonResult::error(null, "编辑用户失败");
        }
    }
    public function delete(Request $request)
    {
        $rules = [
            "id" => "required"
        ];
        if (Validator::make($request->all(), $rules)->fails()) {
            return JsonResult::forbidden(null, "请求参数错误");
        }

        $id = $request->input("id");
        $result = DB::table("users")
            ->where("id", $id)
            ->update(["deleted_at" => now()]);

        if ($result) {
            return JsonResult::success(null, "删除用户成功");
        } else {
            return JsonResult::error(null, "删除用户失败");
        }
    }
    public function setRole(Request $request)
    {
        ini_set("max_execution_time", 0);
        $validator = Validator::make($request->all(), [
            "user_id" => "required",
            "role_ids" => "required"
        ]);
        if ($validator->fails()) {
            return JsonResult::forbidden(null, "请求参数错误");
        }
        //1.将role_ids字符串转化为数组
        $role_ids = explode(",", $request->input("role_ids"));
        //2.获取user_id
        $user_id = $request->input("user_id");
        //3.构建insertData
        $insertData = [];
        foreach ($role_ids as $role_id) {
            $insertData[] = ["user_id" => $user_id, "role_id" => $role_id];
        }

        DB::beginTransaction();
        try {
            //4.删除用户原有的角色
            DB::table("user_roles")->where("user_id", $user_id)->delete();
            //5.insert批量添加
            DB::table("user_roles")->insert($insertData);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return JsonResult::error(null, "服务器错误");
        }

        //6.返回结果
        return JsonResult::success(null, "设置用户角色成功");
    }
    public function uploadAvatar(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'avatar' => 'required|file|mimes:jpg,jpeg,png,gif|max:2048',
        ]);
        if ($validator->fails()) {
            return JsonResult::forbidden(null, '上传文件错误');
        }
        $file = $request->file('avatar');
        $ext = strtolower($file->getClientOriginalExtension());
        $uuid = Str::uuid()->toString();
        $fileName = $uuid . '.' . $ext;
        $path = $file->storeAs('', $fileName, 'avatar'); // avatar为自定义磁盘
        if (!$path) {
            return JsonResult::forbidden(null, '头像上传失败');
        }
        return JsonResult::success(['file_name' => $fileName], '头像上传成功');
    }
    public function getRoles(Request $request)
    {
        $validator = Validator::make($request->all(), [
            "user_id" => "required",
        ]);
        if ($validator->fails()) {
            return JsonResult::forbidden(null, "请求参数错误");
        }

        $user_id = $request->input("user_id");

        // 查询用户的角色
        $roles = DB::table("user_roles as ur")
            ->join("roles as r", "ur.role_id", "=", "r.id")
            ->where("ur.user_id", "=", $user_id)
            ->select("r.*")
            ->get();

        return JsonResult::success($roles, "获取用户角色成功");
    }
}
